import { defineStore } from 'pinia'
import { authApi } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isLoggedIn: false,
    token: null
  }),

  actions: {
    async login(credentials) {
      try {
        const response = await authApi.login(credentials)
        this.isLoggedIn = true
        this.token = response.data
        return response
      } catch (error) {
        throw error
      }
    },

    async logout() {
      try {
        await authApi.logout()
        this.isLoggedIn = false
        this.token = null
      } catch (error) {
        // 即使登出失败也要清除本地状态
        this.isLoggedIn = false
        this.token = null
      }
    },

    async checkStatus() {
      try {
        const response = await authApi.checkStatus()
        this.isLoggedIn = response.data
        return response
      } catch (error) {
        this.isLoggedIn = false
        throw error
      }
    }
  }
})